package com.dangkei.NIO;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class NIORequestProcessor implements Runnable {
    private int bufferSize = 64;
    private SocketChannel socketChannel;

    public NIORequestProcessor(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    public void run() {
        boolean keeplive = false;

        try {
            ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
            socketChannel.read(byteBuffer);
            byteBuffer.flip();      //将缓存操作的位置重新设置到开始
            String req = new String(Charset.forName("UTF-8").decode(byteBuffer).toString());
            //开启keeplive
            keeplive = true;
            System.out.println("线程数量：" + NIOServer.threadPool.getActiveCount() +
                    ", 请求内容： " + req);
            //返回当前时间
            byteBuffer.clear();
            ByteBuffer wrap = ByteBuffer.wrap(("当前时间：" + System.currentTimeMillis()).getBytes());
            socketChannel.write(wrap);
            wrap.clear();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (keeplive) {
                    socketChannel.configureBlocking(false);
                    //注册OP_READ监听
                    socketChannel.register(NIOServer.selector, SelectionKey.OP_READ);
                } else {
                    socketChannel.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
